/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhixinglu.spring.boot.mqtt.tio.listener;

import com.zhixinglu.spring.boot.mqtt.tio.utils.MqttUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.client.MqttClientCreator;
import net.dreamlu.iot.mqtt.spring.client.event.MqttConnectedEvent;
import net.dreamlu.iot.mqtt.spring.client.event.MqttDisconnectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * 客户端连接状态监听
 *
 * @author L.cm
 */
@Slf4j
@Service
public class MqttClientConnectListener {

	@Value("${mqtt.client.name}")
	private String name;

	@Value("${mqtt.client.username}")
	private String username;

	@Value("${mqtt.client.password}")
	private String password;

	@Value("${mqtt.client.ip}")
	private String ip;

	@Value("${mqtt.client.port}")
	private Integer port;


	@Autowired
	private MqttClientCreator mqttClientCreator;

	@EventListener
	public void onConnected(MqttConnectedEvent event) {
		log.info("mqtt connected, {}", event);
	}

	@EventListener
	public void onDisconnect(MqttDisconnectEvent event) {
		log.info("mqtt disconnect reason: {}", event.getReason());
		// 在断线时更新 clientId、username、password
		String clientId = MqttUtil.generateClientId();
		mqttClientCreator.clientId(clientId)
				.name(name)
				.ip(ip)
				.port(port)
				.username(username)
				.password(password);
		log.info("mqtt disconnect new clientId: {}", clientId);
	}

}
